package saas.cloud.remote.configuration;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * feign配置器
 *
 * @author : y1
 * @className : FeignConfiguration
 * @date: 2023/4/11 14:25
 * @description : feign配置器
 */
@Configuration
public class FeignConfiguration implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            //获取头信息
            Map<String, String> headers = getHeaders(request);
            // 传递所有请求头,防止部分丢失
            //将请求的头信息放入到RequestTemplate 的头信息中，当使用RequestTemplate发起请求时会自动添加头信息
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestTemplate.header(entry.getKey(), entry.getValue());
            }
            requestTemplate.header("Interface_ID", "");
            requestTemplate.header("UUID", UUID.randomUUID().toString());
            requestTemplate.header("Messageld", "");
            requestTemplate.header("Sender", "发送方系统名称");
            requestTemplate.header("Receiver", "接收方系统名称");
            requestTemplate.header("SendDate", "发送日期");
            requestTemplate.header("SendTime", "发送时间");
        }
    }

    /**
     * 获取头信息
     *
     * @param request
     * @return
     */
    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        if (enumeration != null) {
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
        }
        return map;
    }

}
